package com.ece.ecofitness.dao;
import java.sql.ResultSet;
import java.sql.SQLException;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ece.ecofitness.jdbcConnection.JdbcConnection;
import com.ece.ecofitness.model.Article;

@Service
public class ArticleDaoImp implements ArticleDao{

	@Autowired
	private JdbcConnection jdbcConnection;

	public boolean addArticle(String admin, String label, String description,int point,String photo) {
		try {
			String sqlrequest="INSERT INTO article VALUES (NULL, '"+admin+"', '"+label+"', '"+description+"', '"+point+"', '"+photo+"', '1', CURRENT_TIMESTAMP)";
			if(jdbcConnection.getStat().executeUpdate(sqlrequest)>0)
			{
				jdbcConnection.getConnection().commit();
				return true;
			}
			else return false;
        
		}
		catch (SQLException e1) {
			return false;
		}
	}

	public boolean updateArticle(int idArticle, String label,String description, int point,String photo)
	{
		try {
			String sqlRequest="";
			description=description.replaceAll("\\t+", "");
			if(photo.isEmpty())
				sqlRequest="update article set label='"+label+"', description='"+description+"' , point='"+point+"' where idArticle='"+idArticle+"'";
			else
				sqlRequest="update article set label='"+label+"', description='"+description+"' , point='"+point+"', photo='"+photo+"' where idArticle='"+idArticle+"'";
			if(jdbcConnection.getStat().executeUpdate(sqlRequest)>0)
			{
				jdbcConnection.getConnection().commit();
				return true;
			}
			else return false;
        
		}
		catch (SQLException e1) {
			return false;
		}
	}

	public List<Article> getAllArticle() {
		try {
			ArrayList<Article> array=new ArrayList<Article>();
			Article article=null;
			ResultSet resultat = jdbcConnection.getStat().executeQuery("SELECT * from article");
			while(resultat.next()){
				
				article=new Article(Integer.parseInt(resultat.getString(1)), resultat.getString(3), resultat.getString(4), Integer.parseInt(resultat.getString(5)),resultat.getString(6));
				
				array.add(article);
			}	
			
			return array;
		} catch (SQLException e) {
			e.printStackTrace();return null;
		} catch (NumberFormatException e) {
			e.printStackTrace();
			return null;
		}
	}

	public Article getArticle(int id) {
		try {
			Article article=null;
			ResultSet resultat = jdbcConnection.getStat().executeQuery("SELECT * from article where idArticle='"+id+"'");
			if(resultat.next()){
				
				article=new Article(Integer.parseInt(resultat.getString(1)), resultat.getString(3), resultat.getString(4), Integer.parseInt(resultat.getString(5)),resultat.getString(6));
			}	
			
			return article;
		} catch (SQLException e) {
			e.printStackTrace();return null;
		} catch (NumberFormatException e) {
			e.printStackTrace();
			return null;
		}
	}
	

}
